const path = require('path');
const P = (_path) => path.resolve(__dirname, _path);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const WebpackBar = require('webpackbar');
const ArcoWebpackPlugin = require('@arco-design/webpack-plugin');
const Dotenv = require('dotenv-webpack');

const baseConfig = {
  entry: P('../src/index.js'),
  output: {
    filename: 'js/[name].js',
    path: P('../dist'),
    publicPath: '/',
    clean: true,
    assetModuleFilename: 'assets/[hash][ext][query]',
  },
  optimization: {
    // 配置 optimization.moduleIds，让公共包 splitChunks 的 hash 不因为新的依赖而改变，减少非必要的 hash 变动
    moduleIds: 'deterministic',
    // minimizer: ['...'],
  },
  module: {
    rules: [
      {
        test: /\.html$/i,
        use: 'html-loader',
      },
      {
        test: /\.(js|jsx)$/i,
        use: 'babel-loader',
        exclude: /node_modules/,
      },

      {
        test: /\.(png|jfif|jpg|svg|gif)$/i,
        type: 'asset/resource',
      },
      {
        test: /\.(ts|tsx)$/i,
        exclude: /node_modules/,
        use: ['ts-loader'],
      },
      {
        test: /\.scss$/i,
        use: [
          // 将 JS 字符串生成为 style 节点
          'style-loader',
          // 将 CSS 转化成 CommonJS 模块
          'css-loader',
          // 将 Sass 编译成 CSS
          'sass-loader',
        ],
      },
    ],
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: P('../public/index.html'),
      scriptLoading: 'blocking',
      favicon: path.resolve(__dirname, '../public/log.jpg'),
    }),
    new ESLintPlugin(),
    new WebpackBar({
      name: 'Daily Learning',
      color: 'green',
    }),
    new ArcoWebpackPlugin(),
    new Dotenv(),
  ],
  resolve: {
    alias: {
      '@': P('../src'),
    },
    extensions: ['.tsx', '.ts', '.jsx', '.js'],
  },
};

module.exports = {
  baseConfig,
  P,
};
